package com.ucap.weking.guangan.views;

import android.content.Context;
import android.support.design.widget.TabItem;
import android.support.design.widget.TabLayout;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;

import com.ucap.weking.guangan.R;

import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.InjectViews;


/**
 * Created by weking on 2017/10/17.
 * 主页底部标签按钮封装
 */

public class TabButton extends FrameLayout {
    @InjectView(R.id.tab_layout)
    TabLayout tabLayout;

    @InjectViews({R.id.iv_home_image1, R.id.iv_home_image2, R.id.iv_home_image3, R.id.iv_home_image4})
    List<ImageView> imageViews;
    OnChange onChange;

    public TabButton(Context context) {
        super(context);
        addContent(context);
    }

    public TabButton(Context context, AttributeSet attrs) {
        super(context, attrs);
        addContent(context);
    }

    public TabButton(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        addContent(context);
    }

    public void setOnChange(OnChange onChange) {
        this.onChange = onChange;
    }

    public void setSelected(int position) {
        tabLayout.getTabAt(position).select();
    }

    public interface OnChange {
        void change(int position);
    }

    private void addContent(Context context) {
        View view = View.inflate(context, R.layout.table_button, null);
        ButterKnife.inject(this, view);
        this.addView(view);
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                setImageSelect(tab.getPosition());
                Log.i("change", "onTabSelected: " + tab.getPosition());
                onChange.change(tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
            }
        });
        setImageSelect(0);//默认选择第一页

    }

    private void setImageSelect(int position) {
        for (int i = 0; i < 4; i++) {
            if (i == position) {
                imageViews.get(i).setSelected(true);
            } else {
                imageViews.get(i).setSelected(false);
            }
            final int finalI = i;
            imageViews.get(i).setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    tabLayout.getTabAt(finalI).select();
                }
            });
        }
    }
}
